﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using General.Mvc.Models;
using General.Entities;
using General.Services.Students;
using General.Core;
using General.Entities.Students;
using General.Core.Data;
using General.Entities.setting;
using Microsoft.EntityFrameworkCore;
using General.Core.UnitOfWork;
using General.Mvc.Filters;
using Consul;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using AutoMapper;
using General.Mvc.Models.Dtos;

namespace General.Mvc.Controllers
{
    public class HomeController : Controller
    {
        private readonly IRepository<Students> studentsRepository;
        private readonly IRepository<setting> settingsRepository;
        private readonly IRepository<setting> asettingsRepository;
        private readonly GeneralDbContext generalDbContext;
        private readonly IUnitOfWork unitOfWork;
        private readonly IConfiguration configuration;
        private readonly ILogger<HomeController> logger;
        private readonly IMapper mapper;
        private static int iSeed = 0;
        //private IStudentsService studentsService;

        //public HomeController(IStudentsService studentsService)
        //{
        //    this.studentsService = studentsService;
        //}

        public HomeController(IRepository<Students> studentsRepository, IRepository<setting> settingsRepository, IRepository<setting> asettingsRepository,GeneralDbContext generalDbContext
            , IUnitOfWork unitOfWork, IConfiguration configuration,ILogger<HomeController> logger,IMapper mapper)
        {
            this.studentsRepository = studentsRepository;
            this.settingsRepository = settingsRepository;
            this.asettingsRepository = asettingsRepository;
            this.generalDbContext = generalDbContext;
            this.unitOfWork = unitOfWork;
            this.configuration = configuration;
            this.logger = logger;
            this.mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        }

        /// <summary>
        /// 主页
        /// </summary>
        /// <returns></returns>
        [ResponseTimeFilterAttribute]
        public IActionResult Index()
        {
            //var list = studentsService.getAll();

            //bool b = Object.ReferenceEquals(asettingsRepository.DbContext, settingsRepository.DbContext);
            //bool c = Object.ReferenceEquals(settingsRepository.DbContext, generalDbContext);


            //EFRepository<Students> db = new EFRepository<Students>();
            return View();
        }



        /// <summary>
        /// 获取consul全部服务
        /// </summary>
        /// <returns></returns>
        public IActionResult GetConsul()
        {
            using (ConsulClient client = new ConsulClient(c =>
            {
                c.Address = new Uri(configuration["ConsulUrl"]);
                c.Datacenter = "dc1";
            }))
            {
               var dictionary =  client.Agent.Services().Result.Response;
                //foreach (var item in dictionary)
                //{
                //    AgentService agentService = item.Value;
                //    logger.LogWarning(agentService.Address+":"+agentService.Port+" "+agentService.ID +" "+agentService.Service );
                    
                //}
                var list = dictionary.Where(x=>x.Value.Service.Equals("GeneralNetCore",StringComparison.OrdinalIgnoreCase));
                //均衡策略
                //var item = list.ToArray()[new Random().Next(0,list.Count())];
                //轮训策略
                //var item = list.ToArray()[iSeed++ % list.Count()];
                //权重策略
                var pairsList = new List<KeyValuePair<string, AgentService>>();
                foreach (var pair in list)
                {
                    int count  = int.Parse(pair.Value.Tags?[0]);
                    for (int i = 0; i < count; i++)
                    {
                        pairsList.Add(pair);
                    }
                }
                var item = pairsList.ToArray()[new Random(iSeed++).Next(0, pairsList.Count())];


            };
            return Content("");
        }



        /// <summary>
        /// mapper test
        /// </summary>
        /// <returns></returns>
        public IActionResult AutoMapperTest()
        {
            List<Students> ts = new List<Students>() { new Students() { id=1, name="张三", pwd="123456" } };
            var list = mapper.Map<List<StudentsDto>>(ts);
            //return Json(list);
            return Content(JsonHelper.Serialize(list));
        }


        public IActionResult HealthCheck()
        {
            return Ok();
        }


        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
